package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.dto.ArticleDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-10
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;

    //app端文章保存接口
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        // 需求分析
        ApArticle article=new ApArticle();
        BeanUtils.copyProperties(dto,article);
        //判断id是否为空
        if (article.getId()==null) {
            //保存文章表
            article.setCreatedTime(new Date());
            this.save(article);
            //保存内容表
            ApArticleContent content=new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentService.save(content);
            //返回通用响应
            return ResponseResult.okResult(article.getId());

        }else {
            //修改文章
            this.updateById(article);
            //修改文章内容
            LambdaUpdateWrapper<ApArticleContent> query=new LambdaUpdateWrapper<>();
            query.eq(ApArticleContent::getArticleId,dto.getId());
            query.set(ApArticleContent::getContent,dto.getContent());
            contentService.update(query);
            return ResponseResult.okResult(article.getId());

        }
    }
}
